const express = require('express')
const mysql = require('mysql2/promise')
const cors = require('cors')
const bodyParser = require('body-parser')

const app = express()
app.use(cors())
app.use(bodyParser.json())

const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'Qwe54188_',
  database: 'vue_exam',
  port: 3306
})

// ✅ 用户登录，存在就返回，不存在就注册
app.post('/api/login', async (req, res) => {
  const { name, employeeId, confirmEmployeeId } = req.body
  if (!name || !employeeId || !confirmEmployeeId) {
    return res.status(400).json({ message: '用户名和工号不能为空' })
  }
  if (employeeId !== confirmEmployeeId) {
    return res.status(400).json({ message: '两次工号不一致' })
  }
  if (name === 'admin') {
    return res.status(403).json({ message: '管理员请使用专用入口登录' })
  }
  try {
    const [rows] = await pool.query('SELECT * FROM user WHERE name = ?', [name])
    if (rows.length > 0) {
      // 用户已存在，校验密码
      if (rows[0].employeeId !== employeeId) {
        return res.status(401).json({ message: '密码错误' })
      }
      // 密码正确，允许登录
      return res.json({ role: 'user', message: '登录成功' })
    } else {
      // 用户不存在，注册
      await pool.query('INSERT INTO user (name, employeeId) VALUES (?, ?)', [name, employeeId])
      return res.json({ role: 'user', message: '注册并登录成功' })
    }
  } catch (err) {
    res.status(500).json({ message: '数据库错误', error: err.message })
  }
})

// ✅ 管理员登录
app.post('/api/admin/login', async (req, res) => {
  const { employeeId } = req.body
  if (!employeeId) return res.status(400).json({ message: '请输入工号' })
  try {
    const [rows] = await pool.query('SELECT * FROM admin WHERE employee_id = ?', [employeeId])
    if (rows.length === 0) return res.status(401).json({ message: '管理员不存在' })
    res.json({ role: 'admin', admin_name: rows[0].admin_name, message: '管理员登录成功' })
  } catch (err) {
    res.status(500).json({ message: '数据库错误', error: err.message })
  }
})

// ✅ 只保留最高分
app.post('/api/submit-score', async (req, res) => {
  const { employeeId, duration, score } = req.body
  if (!employeeId || typeof score !== 'number' || typeof duration !== 'number') {
    return res.status(400).json({ message: '参数不完整' })
  }
  try {
    const [rows] = await pool.query(
      'SELECT score FROM user_score WHERE employeeId = ?',
      [employeeId]
    )
    if (rows.length === 0) {
      // 没有记录，插入
      await pool.query(
        'INSERT INTO user_score (employeeId, duration, score, exam_date) VALUES (?, ?, ?, NOW())',
        [employeeId, duration, score]
      )
      return res.json({ message: '成绩已记录' })
    } else if (score > rows[0].score) {
      // 有记录且新分数更高，更新
      await pool.query(
        'UPDATE user_score SET score = ?, duration = ?, exam_date = NOW() WHERE employeeId = ?',
        [score, duration, employeeId]
      )
      return res.json({ message: '新高分，成绩已更新' })
    } else {
      // 分数不高，不更新
      return res.json({ message: '分数未超过历史最高分，不做更新' })
    }
  } catch (err) {
    res.status(500).json({ message: '分数提交失败', error: err.message })
  }
})



// ✅ 用户查询成绩
app.get('/api/get-score', async (req, res) => {
  const { employeeId } = req.query
  if (!employeeId) return res.status(400).json({ message: '缺少参数' })
  try {
    const [rows] = await pool.query(
      'SELECT score, duration, exam_date FROM user_score WHERE employeeId = ? ORDER BY exam_date DESC',
      [employeeId]
    )
    res.json({ scores: rows })
  } catch (err) {
    res.status(500).json({ message: '查询失败', error: err.message })
  }
})

// ✅ 管理员查询所有成绩（关联 user 获取姓名）
app.get('/api/admin/user-scores', async (req, res) => {
  try {
    const [rows] = await pool.query(`
      SELECT 
        u.name,
        s.employeeId,
        s.score,
        s.duration,
        s.exam_date
      FROM user_score s
      LEFT JOIN user u ON s.employeeId = u.employeeId
      ORDER BY s.exam_date DESC
    `)
    res.json({ data: rows })
  } catch (err) {
    res.status(500).json({ message: '查询失败', error: err.message })
  }
})

app.listen(3000, () => {
  console.log('后端服务已启动，端口3000 ✅')
})
